import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../stores/index'
import { Upload as AntUpload, Form, Input, Button, Select, message, Modal } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { myAxios } from '../axios'
import './Upload.less'

const { Option } = Select

const Upload = () => {
  const navigate = useNavigate()
  const store = useStore()
  const userdata = store.userdata

  const [students, setStudents] = useState([])
  const [selectedStudent, setSelectedStudent] = useState(null)
  const [showForm, setShowForm] = useState(false)
  const [loading, setLoading] = useState(true)

  const [formData, setFormData] = useState({
    title: '',
    description: '',
    location: '',
    helpType: 'offline',
    subject: '',
    frequency: '',
    duration: ''
  })

  const [errors, setErrors] = useState({})

  useEffect(() => {
    fetchStudents()
  }, [])

  const fetchStudents = async () => {
    try {
      const res = await myAxios.get('/stu/find')
      if (res.data.code === 200) {
        if (res.data.data && res.data.data.length > 0) {
          setStudents(res.data.data)
        } else {
          message.warning('您还没有添加任何学生信息，请在个人数据中添加学生信息',2)
          navigate('/home/user', { state: { scrollToBottom: true } })
        }
      } else {
        message.error(res.data.message || '获取学生信息失败')
        navigate('/home/market')
      }
    } catch (error) {
      console.error('获取学生信息失败:', error)
      message.error('获取学生信息失败')
      navigate('/home/market')
    } finally {
      setLoading(false)
    }
  }

  const handleStudentSelect = (student) => {
    setSelectedStudent(student)
    setShowForm(true)
  }

  const handleInputChange = (e) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
    if (errors[name]) {
      setErrors(prev => ({
        ...prev,
        [name]: ''
      }))
    }
  }

  const validateForm = () => {
    const newErrors = {}
    
    if (!formData.title.trim()) {
      newErrors.title = '请输入标题'
    }
    if (!formData.description.trim()) {
      newErrors.description = '请输入详细描述'
    }
    if (!formData.location.trim()) {
      newErrors.location = '请输入地址'
    }
    if (!formData.subject.trim()) {
      newErrors.subject = '请输入科目'
    }
    if (!formData.frequency.trim()) {
      newErrors.frequency = '请输入授课频率'
    }
    if (!formData.duration.trim()) {
      newErrors.duration = '请输入每次时长'
    }

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    
    if (!validateForm()) {
      return
    }
    


  const submitData = {
    userId: store.userdata.id,
    studentId: selectedStudent.studentId,
    title: formData.title,
    description: formData.description,
    location: formData.location,
    status: 'pending',
    helpType: formData.helpType,
    subject: formData.subject,
    frequency: formData.frequency,
    duration: formData.duration
  }

  console.log('提交的数据:', submitData)
  
    // 详细打印每个字段的类型和值
    console.log('提交数据详情:')
    Object.entries(submitData).forEach(([key, value]) => {
      console.log(`${key}: `, value, `(类型: ${typeof value})`)
    })
  
    setLoading(true)
    try {
      // 打印完整的请求URL和方法
      console.log('请求URL: /help/add')
      console.log('请求方法: POST')
      console.log('请求数据:', submitData)
  
      const res = await myAxios.post('/help/add', submitData)
      console.log('服务器响应:', res)
      
      if (res.data.code === 200) {
        message.success('发布成功')
        navigate('/home/market')
      } else {
        console.log('错误响应:', res.data)
        message.error(res.data.message || '发布失败')
      }
    } catch (error) {
      console.error('错误详情:', {
        message: error.message,
        response: error.response,
        request: error.request,
        config: error.config
      })
      message.error('发布失败，请稍后重试')
    } finally {
      setLoading(false)
    }
  }
  const formatDate = (dateString) => {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}年${month}月${day}日`;
  }

  return (
    <div className="upload-container">
      {loading ? (
        <div className="loading">加载中...</div>
      ) : !showForm ? (
        <div className="upload-card">
          <h1 className="title">选择学生</h1>
          <div className="student-list">
            {students.map(student => (
              <div
                key={student.studentId}
                className="student-card"
                onClick={() => handleStudentSelect(student)}
              >
                <div className="student-info">
                  <h3>{student.fullName}</h3>
                  <div className="info-row">
                    <span>性别: {student.gender === 'Male' ? '男' : '女'}</span>
                  </div>
                  <div className="info-row">
                    <span>生日: {formatDate(student.birthdate)}</span>
                  </div>
                  <div className="info-row">
                    <span>学校: {student.school}</span>
                  </div>
                  <div className="info-row">
                    <span>年级: {student.grade}</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div className="upload-card">
          <h1 className="title">发布辅导需求</h1>
          <div className="selected-student">
            已选择学生：{selectedStudent.fullName}
            <button 
              className="change-student" 
              onClick={() => setShowForm(false)}
            >
              更换
            </button>
          </div>

          <form onSubmit={handleSubmit} className="upload-form">
            <div className="form-section">
              <h3 className="section-title">基本信息</h3>
              <div className="form-row full-width">
                <div className="form-group">
                  <label>标题<span className="required">*</span></label>
                  <input
                    type="text"
                    name="title"
                    value={formData.title}
                    onChange={handleInputChange}
                    placeholder="请输入标题"
                    className={errors.title ? 'error' : ''}
                  />
                  {errors.title && <span className="error-message">{errors.title}</span>}
                </div>
              </div>
            </div>

            <div className="form-section">
              <h3 className="section-title">辅导需求</h3>
              <div className="form-row">
                <div className="form-group">
                  <label>授课方式</label>
                  <select
                    name="helpType"
                    value={formData.helpType}
                    onChange={handleInputChange}
                  >
                    <option value="offline">线下</option>
                    <option value="online">线上</option>
                  </select>
                </div>

                <div className="form-group">
                  <label>科目<span className="required">*</span></label>
                  <input
                    type="text"
                    name="subject"
                    value={formData.subject}
                    onChange={handleInputChange}
                    placeholder="请输入科目"
                    className={errors.subject ? 'error' : ''}
                  />
                  {errors.subject && <span className="error-message">{errors.subject}</span>}
                </div>
              </div>

              <div className="form-row">
                <div className="form-group">
                  <label>授课频率<span className="required">*</span></label>
                  <input
                    type="text"
                    name="frequency"
                    value={formData.frequency}
                    onChange={handleInputChange}
                    placeholder="例如：每周两次"
                    className={errors.frequency ? 'error' : ''}
                  />
                  {errors.frequency && <span className="error-message">{errors.frequency}</span>}
                </div>

                <div className="form-group">
                  <label>每次时长<span className="required">*</span></label>
                  <input
                    type="text"
                    name="duration"
                    value={formData.duration}
                    onChange={handleInputChange}
                    placeholder="例如：1.5小时/次"
                    className={errors.duration ? 'error' : ''}
                  />
                  {errors.duration && <span className="error-message">{errors.duration}</span>}
                </div>
              </div>

              <div className="form-row full-width">
                <div className="form-group">
                  <label>地址<span className="required">*</span></label>
                  <input
                    type="text"
                    name="location"
                    value={formData.location}
                    onChange={handleInputChange}
                    placeholder="请输入地址"
                    className={errors.location ? 'error' : ''}
                  />
                  {errors.location && <span className="error-message">{errors.location}</span>}
                </div>
              </div>

              <div className="form-row full-width">
                <div className="form-group">
                  <label>详细描述<span className="required">*</span></label>
                  <textarea
                    name="description"
                    value={formData.description}
                    onChange={handleInputChange}
                    placeholder="请详细描述您的辅导需求"
                    className={errors.description ? 'error' : ''}
                  />
                  {errors.description && <span className="error-message">{errors.description}</span>}
                </div>
              </div>
            </div>

            <div className="form-footer">
              <button type="button" className="cancel-btn" onClick={() => navigate('/home/market')}>
                取消
              </button>
              <button type="submit" className="submit-btn" disabled={loading}>
                {loading ? '发布中...' : '发布'}
              </button>
            </div>
          </form>
        </div>
      )}
    </div>
  )
}

export default Upload